package com.kyzh.core.pager.weal.gift

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.http.SslError
import android.os.Bundle
import android.util.Log
import android.webkit.*
import com.gushenge.core.base.Base
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.dao.MMKVConsts.sub
import com.gushenge.core.dao.MMKVConsts.uid
import com.kyzh.core.R
import com.kyzh.core.utils.httpSign
import com.kyzh.core.utils.setVisibility
import com.kyzh.core.utils.time
import com.gushenge.core.toast
import com.kyzh.core.pager.weal.coupon.ZJLSActivity
import kotlinx.android.synthetic.main.activity_gift_ocoupon.*
import kotlinx.android.synthetic.main.activity_gift_ocoupon.webview
import org.jetbrains.anko.browse
import org.jetbrains.anko.startActivity
import java.util.*

class GiftOCouponRecordActivity : BaseActivity() {
    companion object{
        @JvmStatic
        fun start(context: Context,type:Int,url : String,gid:String) {
            Log.e("TAG", "start: $url", )
            val starter = Intent(context, GiftOCouponRecordActivity::class.java)

                .putExtra("type",type) .putExtra("link",url) .putExtra("gid",gid)
            context.startActivity(starter)
        }
    }
    /**
     * 0 失败   1 礼包   2 优惠券
     */
    var  type:Int? = null
    private var link: String? = null
    private var name: String? = null
    private var gid: String? = null
    private var canClose = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gift_ocoupon)
        type=intent.getIntExtra("type",0)
        link=intent.getStringExtra("link")
        gid = intent.getStringExtra("gid")
        Log.e("TAG", "onCreate: $link", )
        initView()
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initView() {
        when(type){
            1 ->  {
                tvTitle.text= "领取礼包"
                tv_jilu.setVisibility(true)
            }

            2 -> {
                tvTitle.text= "领取优惠券"
                tv_jilu.setVisibility(true)
            }
            3 -> {
                tvTitle.text= "优惠券领取记录"
                tv_jilu.setVisibility(false)
            }
            4 -> {
                tvTitle.text= "礼包领取记录"
                tv_jilu.setVisibility(false)
            }
            else -> finish()
        }
        close.setOnClickListener {
            finish()
        }
//
        tv_jilu.setOnClickListener {
            val time1 = time
            val httpSign = httpSign(uid + time1)
            var  url = ""
            if(type == 2){
                url = Base.BASEURL+"/?ct=app2021&ac=coupon_log&uid=${uid}&t=$time1&sign=$httpSign&gid=$gid&member_id=${sub}"
                start(this,3,url,gid!!)
            }else if(type ==1){
                url = Base.BASEURL+"/?ct=app2021&ac=lb_log&uid=${uid}&t=$time1&sign=$httpSign&gid=$gid&member_id=${sub}"
                start(this,4,url,gid!!)
            }


        }
        val webSettings = webview.settings
        webSettings.allowFileAccess = true// 设置允许访问文件数据
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.domStorageEnabled = true
        webSettings.databaseEnabled = true
        // 关键性代码，这里要给webview添加这行代码，才可以点击之后正常播放音频。记录一下。
        webSettings.mediaPlaybackRequiresUserGesture = false

        //设置WebView属性，能够执行Javascript脚本
        webSettings.javaScriptEnabled = true
        webview.loadUrl(link?:"")
//        root.setOnRefreshListener { webview.reload() }
        webview.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                if (name != "隐私政策" && name != "注册协议") {
                    tvTitle.setText(title ?: "")
                }
            }
        }
        webview.webChromeClient = object : WebChromeClient() {
            override fun onJsAlert(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult?
            ): Boolean {
                when (message) {
                    "中奖记录" -> {
                        result?.cancel()
                        startActivity<ZJLSActivity>()
                        return true
                    }
                    else -> {
                        message?.toast()
                        result?.cancel()
                        return true
                    }
                }
                return true
            }

        }
        webview.webViewClient = object : WebViewClient() {
            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                super.onReceivedSslError(view, handler, error)
                handler?.proceed()
            }
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                if (url.startsWith("http")) {
                    //处理http和https开头的url
                    val extraHeaders = HashMap<String,String>()
                    extraHeaders["Referer"] = Base.BASEURL
                    view.loadUrl(url, extraHeaders)
                    return true
                }else{
                    browse(url)
                    return true
                }
            }

            override fun onPageFinished(view: WebView, url: String) {
                tvTitle.text = view.title
                val js = "javascript:(function() {document.getElementById(\"j_page_header\").style.display=\'none\';" + "})()"
                view.loadUrl(js)
                super.onPageFinished(view, url)
            }
        }
    }

    override fun onBackPressed() {
        if (webview.canGoBack()){
            webview.goBack()
        }else{
            finish()
        }
    }

    /*没用... override fun onResume() {
         super.onResume()
         webview.onResume()
         webview.resumeTimers()
         webview.reload()
     }

     override fun onPause() {
         super.onPause()
         webview.onPause()
         webview.pauseTimers()
     }*/
    override fun onRestart() {
        super.onRestart()
        if (canClose) finish()
    }
}